﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace RollbackLib.src.utils
{
    /// <summary>
    /// List of utility functions for encryption and decryption data
    /// </summary>
    public class Crypto
    {
        private static byte[] m_Salt = new byte[] { 0x93,0x5,0x36,0x1,0x12,0xa8,0xa7,0xd3,0x5c,0x27,0x8d};
        private Rijndael rinjdael;

        public Crypto(String password) 
        {
            Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(password,m_Salt);
            rinjdael = Rijndael.Create();
            rinjdael.Key = db.GetBytes(32);
            rinjdael.IV = db.GetBytes(16);
        }

        public String Encrypt(String plain)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                CryptoStream cryptStream = new CryptoStream(memStream, rinjdael.CreateEncryptor(), CryptoStreamMode.Write);
                byte[] b = Encoding.UTF8.GetBytes(plain);
                cryptStream.Write(b, 0, b.Length);
                cryptStream.FlushFinalBlock();
                String encrypted = Convert.ToBase64String(memStream.ToArray());
                return encrypted;
            }
        }

        public String Decrypt(String encrypted)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                CryptoStream cryptStream = new CryptoStream(memStream, rinjdael.CreateDecryptor(), CryptoStreamMode.Write);
                byte[] b = Convert.FromBase64String(encrypted);
                cryptStream.Write(b, 0, b.Length);
                cryptStream.FlushFinalBlock();
                String decrypted = Encoding.UTF8.GetString(memStream.ToArray());
                return decrypted;
            }
        }
    }
}
